#ifndef PACKET_H
#define PACKET_H

/* ---<>-----------------------------------
        Includes
---------------------------------------- */
#include "ftd2xx.h"
#include <vector>

using namespace std;

/* ---<>-----------------------------------
        Packet Class
---------------------------------------- */
class packet
{
public:
    vector<unsigned char> data;
    packet() { data.push_back('U'); crc = 0; }
    ~packet() {}
    void reset() { data.clear(); data.push_back('U'); crc = 0; }

    DWORD sendPacket(FT_HANDLE ftHandle)
    {
        if (crc == 0) { this->createCRC(); }
        //for (int ii = 0; ii < data.size(); ii++) { printf("%02x-",data[ii]); } printf("\n\n");
        DWORD bytesWritten;
        FT_Write(ftHandle, data.data(), data.size(), &bytesWritten);
        return bytesWritten;
    }
private:
    bool crc;
    void createCRC()
    {
        uint16_t shiftRegister = 0xFFFF;
        uint16_t x;
        for (int ii = 0; ii < data.size(); ii++)
        {
            x = ((shiftRegister >> 8) ^ data[ii]) & 0xFF;
            x ^= x >> 4;
            shiftRegister = (shiftRegister << 8) ^ (x << 12) ^ (x << 5) ^ x;
        }
        //printf("CRC Code: %d First: %x | Second: %x \n\n",shiftRegister,(shiftRegister & 0xFF00) >> 8, shiftRegister & 0xFF );
        data.push_back((shiftRegister & 0xFF00) >> 8);
        data.push_back(shiftRegister & 0xFF);
        crc = 1;
    }
};

#endif // PACKET_H
